package com.tycoin.app.controller;

import com.tycoin.account.slaveservice.TycoinAccountService;
import com.tycoin.app.response.BaseRespose;
import com.tycoin.user.slaveentity.TycoinUser;
import com.tycoin.user.slaveentity.TycoinUserLoginLog;
import com.tycoin.user.slaveservice.TycoinUserLoginLogService;
import com.tycoin.user.slaveservice.TycoinUserService;
import com.tycoin.utils.VerifyEmail;
import com.util.DateUtils;
import com.util.MD5Utils;
import com.util.PhoneFormatCheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by happy on 2017/8/31.
 */

@RestController
@RequestMapping(value = { "/api" })
public class ApiController extends UserController{
    @Autowired
    private TycoinUserService tycoinUserService;
    @Autowired
    private TycoinAccountService tycoinAccountService;
    @Autowired
    private TycoinUserLoginLogService tycoinUserLoginLogService;
    @Autowired
    private BaseRespose baseRespose;
    private String resetCode;
    private String emailCode;
    private   int PAGENUM=5;


    /**
     * 除登录，注册，首次绑定微信外，别的功能先调用本方法判断 AccessToken
     * @param request
     * @param response
     * @return -1,
     * @throws UnsupportedEncodingException
     */

    public BaseRespose checkAccessToken(HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException {
//        测试用，正式跳过。
        if (true){
            baseRespose.setCode(200);
            return baseRespose;
        }
        String accessToken=request.getParameter("accessToken");
        if (accessToken==null){
            baseRespose.setCode(4013);
            return baseRespose;
        }
        String strings[]=accessToken.split("-");
        if (strings==null||strings.length!=2)
        {
            baseRespose.setCode(4013);
            return baseRespose;
        }
        TycoinUser tycoinUser = tycoinUserService.findById(Long.valueOf(strings[1]));
        if (tycoinUser==null)
        {
            baseRespose.setCode(4013);
            return baseRespose;
        }
        long time=new Date().getTime();
        if (time-tycoinUser.getUpdateTime().getTime()>7200)//距离上次登录小于7200
        {
            baseRespose.setCode(4013);
            return baseRespose;
        }
        baseRespose.setCode(200);
        return baseRespose;
//        Cookie cookie = new Cookie("userInfo", "userName:" + java.net.URLEncoder.encode(userName, "UTF-8")
//                + ",passWord:" + tycoinUser.getPassword() + ",userId:" + tycoinUser.getId());
//        cookie.setMaxAge(7200);
//        cookie.setPath("/");
//        response.addCookie(cookie);
//        request.getSession().setAttribute("userName", userName);
//        request.getSession().setAttribute("passWord", tycoinUser.getPassword());
//        request.getSession().setAttribute("userId", tycoinUser.getId());
//        updateLoginLog(tycoinUser,request);
//        // TODO: 2017/8/31 简单随机生产Access_tonken， 待后续优化
//        StringBuffer buffer=new StringBuffer(UUID.randomUUID().toString().replaceAll("-", ""));
//        buffer.append("-");
//        buffer.append(tycoinUser.getId());
//        tycoinUser.setAccess_token(buffer.toString());
//        tycoinUserService.save(tycoinUser);
//        baseRespose.setCode(200);
//        baseRespose.setData(tycoinUser);
//        return  baseRespose;
    }

    @Autowired
    HomeController homeController;


    /********
     * 完善更新用户资料
     * @param request
     * @param response
     * @return
     */
    @RequestMapping({ "/updateUserInfo" })
    public BaseRespose  updateUserInfo(HttpServletRequest request, TycoinUser tycoinUser,HttpServletResponse response) throws UnsupportedEncodingException {
        if (checkAccessToken(request,response).getCode()==200){
            return homeController.updateUserInfo(request,tycoinUser,response);
        }
       return checkAccessToken(request,response);

    }





        /*****
         * 上传图片
         * @param file
         * @param request
         * @param response
         * @param memberCode
         * @return
         * @throws IOException
         */
    @RequestMapping("/uploadIdCard")
    public  BaseRespose uploadIdCard(@RequestParam(value="imgFile",required=false) MultipartFile[] file, HttpServletRequest request, HttpServletResponse response, String memberCode) throws IOException {
        response.setHeader("Access-Control-Allow-Origin","*");
        if (checkAccessToken(request,response).getCode()==200)
            return homeController.uploadIdCard(file,request,response,memberCode);
        return checkAccessToken(request,response);
    }


    @RequestMapping(value = "/setPayPasswd",method = RequestMethod.POST)
    public BaseRespose setPayPasswd(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        if (checkAccessToken(request,response).getCode()==200)
            return super.setPayPasswd(request,response);
        return checkAccessToken(request,response);
    }


    /*************
     * 绑定微信openid
     * @param request
     * @param response
     * @return
     */
        @RequestMapping(value = "/bindWeChat", produces = "application/json;charset=UTF-8")
    public BaseRespose bindWeChat(HttpServletRequest request, HttpServletResponse response){
            String phone= null;
            String wechat = null;
            try {
                phone = request.getParameter("mobilephone");
                wechat = request.getParameter("wechat");
            } catch (Exception e) {
            baseRespose.setData(4001);
            baseRespose.setMassage("error");
            return baseRespose;
            }
            TycoinUser tycoinUser = tycoinUserService.findOneBymobile(phone);
            if (tycoinUser==null){
            baseRespose.setData(4006);
            baseRespose.setMassage("error");
            return baseRespose;
            }
            tycoinUser.setWeixin(wechat);
            StringBuffer buffer=new StringBuffer(UUID.randomUUID().toString().replaceAll("-", ""));
            buffer.append("-");
            buffer.append(tycoinUser.getId());
            tycoinUser.setAccess_token(buffer.toString());
            updateLoginLog(tycoinUser,request);
            tycoinUserService.save(tycoinUser);
            baseRespose.setData(tycoinUser);
            baseRespose.setCode(200);
            return baseRespose;
    }



    @RequestMapping(value = "/checkBindWechat", produces = "application/json;charset=UTF-8")
    public BaseRespose checkBindWechat(HttpServletRequest request, HttpServletResponse response){
        String wechat = request.getParameter("wechat");
        TycoinUser tycoinUser = tycoinUserService.findOneByweixin(wechat);
        if (tycoinUser==null){
            baseRespose.setCode(4015);
            return baseRespose;
        }

        StringBuffer buffer=new StringBuffer(UUID.randomUUID().toString().replaceAll("-", ""));
        buffer.append("-");
        buffer.append(tycoinUser.getId());
        tycoinUser.setAccess_token(buffer.toString());
        updateLoginLog(tycoinUser,request);
        tycoinUserService.save(tycoinUser);
        baseRespose.setData(tycoinUser);
        baseRespose.setCode(200);
        return baseRespose;

    }
    @RequestMapping(value = "/checkMobile", produces = "application/json;charset=UTF-8")
    public BaseRespose checkMobile(HttpServletRequest request,HttpServletResponse response) {
        String mobilePhone=request.getParameter("mobilephone");
        TycoinUser tycoinUser=tycoinUserService.findOneBymobile(mobilePhone);
        if (tycoinUser==null){
            baseRespose.setCode(502);
            baseRespose.setMassage("手机号可以注册");
            return baseRespose;
        }
        baseRespose.setCode(200);
        baseRespose.setMassage("手机号已经注册");
        return baseRespose;
    }

    @RequestMapping(value = "/bindOrRegister", produces = "application/json;charset=UTF-8")
    public BaseRespose bindOrRegister(HttpServletRequest request,HttpServletResponse response) throws Exception {
            response.setHeader("Access-Control-Allow-Origin","*");
            if (checkMobile(request,response).getCode()==502)
            {
                Map<String, Object> map=register(request,response);
                int code= (int) map.get("code");
                baseRespose.setCode(code);
                return baseRespose;
            }else {
                return bindWeChat(request,response);
            }
    }



    @RequestMapping(value = "/login", produces = "application/json;charset=UTF-8")
    public BaseRespose login(HttpServletRequest request, HttpServletResponse response){
        TycoinUser tycoinUser=null;
        String passWord = request.getParameter("passWord");
        String userName = request.getParameter("userName");
        String phone = request.getParameter("phone");
        String wechat = request.getParameter("wechat");
        String email=request.getParameter("email");
        if (passWord==null||passWord.length()<6){
            baseRespose.setCode(4006);
            return baseRespose ;
        }
        if (userName!=null)
            tycoinUser = tycoinUserService.findOneByusername(userName);
        if (tycoinUser==null&&wechat!=null)
            tycoinUser=tycoinUserService.findOneByweixin(wechat);
        if (tycoinUser==null&&email!=null)
            tycoinUser=tycoinUserService.findOneByemail(email);
        if (tycoinUser==null&&phone!=null)
            tycoinUser=tycoinUserService.findOneBymobile(phone);
        if (tycoinUser==null){
            baseRespose.setCode(4006);
            return baseRespose;
        }
        String salt = tycoinUser.getSalt();
        MD5Utils encoderMd5 = new MD5Utils(salt, "MD5");
        System.out.println(tycoinUser.getPassword());
        boolean passwordValid = encoderMd5.isPasswordValid(tycoinUser.getPassword(), passWord);
        if (!passwordValid){
            baseRespose.setCode(4010);
            return baseRespose;
        }
        StringBuffer buffer=new StringBuffer(UUID.randomUUID().toString().replaceAll("-", ""));
        buffer.append("-");
        buffer.append(tycoinUser.getId());
        tycoinUser.setAccess_token(buffer.toString());
        updateLoginLog(tycoinUser,request);
        tycoinUserService.save(tycoinUser);
        baseRespose.setData(tycoinUser);
        baseRespose.setCode(200);
        return baseRespose;
    }



    public void updateLoginLog(TycoinUser tycoinUser,HttpServletRequest request){
        TycoinUserLoginLog tycoinUserLoginLog=new TycoinUserLoginLog();

        tycoinUserLoginLog.setUserId(tycoinUser.getId());
        tycoinUserLoginLog.setLoginTime(DateUtils.formatDateTime3(new Date()));
        tycoinUserLoginLog.setIp(getIpAddr(request));
        String addresss=findIpToAddress(tycoinUserLoginLog.getIp());
        tycoinUserLoginLog.setAddress(addresss);
        try {
            String clinet = request.getParameter("clinet");
            tycoinUserLoginLog.setClient(clinet);
        } catch (Exception e) {}

        tycoinUserLoginLogService.save(tycoinUserLoginLog);
        /******
         *
         */
        tycoinUser.setIntegral(tycoinUser.getIntegral()+2);
        tycoinUser.setLastloginip(tycoinUserLoginLog.getIp());
    }


    /*********
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/sendVCode")
    public BaseRespose sendVCode(HttpServletRequest request,HttpServletResponse response,String msgTemplate) {
        String mobile=request.getParameter("mobile");
        TycoinUser user=tycoinUserService.findOneBymobile(mobile);
        if (user==null)
        {
            baseRespose.setCode(4008);
            baseRespose.setMassage("手机号码错误");
            return baseRespose;
        }
        resetCode = DateUtils.getYzm();
        String msg=sendMsgToMoblile(user.getMobile(),resetCode);
        baseRespose.setCode(200);
        baseRespose.setMassage(resetCode);
        return baseRespose;
    }
}
